const BaseIpcHandler = require('../BaseIpcHandler');
const fs = require('fs');

class DeleteTrainRecordHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log('>> DeleteTrainRecordHandler params = ', params);
        const { record_id } = params;

        // 业务逻辑
        let result = null;
        try {
            let records = await this.app.db.train_records.getRecord(record_id);
            if (records.length === 0) {
                result = { code: -1, msg: `Record with ID ${record_id} not found` };
            } else {
                let record = records[0];
                let output_dir = record.output_dir;
                if (fs.existsSync(output_dir)) {
                    fs.rmSync(output_dir, { recursive: true });
                }

                await this.app.db.train_records.delete(record_id);
                result = { code: 0, msg: 'Delete Record OK!' };
            }
        } catch (err) {
            console.error(`Error get train records: `, err);
            result = { code: -1, msg: err.message };
        }

        // 返回结果
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = DeleteTrainRecordHandler;
